package com.wkc;

import java.util.Timer;
import java.util.TimerTask;

import wwk.common.util.DateTimeUtil;
import wwk.common.widget.CustomDialog;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MediaPlayerActivity extends Activity implements VideoPlayerInterface
{
    private SurfaceView surfaceView;
    private String videoUrl;
    
    private TextView titleTextView;
    private SeekBar seekBar;
    private float seekToPercent;
    private TextView timeTextView;
    private ImageButton playButton;
    private ImageButton playButtonLarge;
    private VideoPlayer videoPlayer;
    private View topLayer;
    private View bottomLayer;
    private View middleLayer;
    
    private Timer mTimer;
	private TimerTask mTimerTask;
	
	private Handler handler=new Handler() 
	{
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			
			switch(msg.what)
			{
				case 0:
					{
						topLayer.setVisibility(View.INVISIBLE);
		    				bottomLayer.setVisibility(View.INVISIBLE);
		    				cancelTimer();
					}
					break;
			}
		}
	};

    @Override
    public void onCreate(Bundle icicle) 
    {
        super.onCreate(icicle);
        setContentView(R.layout.media_player_activity);
        
        //required for fullscreen
        getWindow().setFlags( 
        		WindowManager.LayoutParams.FLAG_FULLSCREEN,
        		WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        /*如果要退出全屏模式：
			mHold.setFixedSize(800, 800);
            getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        */        
        
        topLayer = findViewById(R.id.topLayer);
        bottomLayer = findViewById(R.id.controlLayer);
        middleLayer = findViewById(R.id.middleLayer);
        topLayer.setClickable(true);
        bottomLayer.setClickable(true);
        
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        surfaceView.setOnTouchListener(new OnTouchListener()
        {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) 
			{
				cancelTimer();
				
				boolean isVisible=topLayer.getVisibility()==View.VISIBLE;
				if(isVisible)
				{
					topLayer.setVisibility(View.INVISIBLE);
					bottomLayer.setVisibility(View.INVISIBLE);
				}
				else
				{
					topLayer.setVisibility(View.VISIBLE);
					bottomLayer.setVisibility(View.VISIBLE);
					
					////startTimer();
				}

				return false;
			}
        });
        titleTextView = (TextView)findViewById(R.id.titleTextView);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
        		{
					@Override
					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) 
					{
						// 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
						//Log.d("onProgressChanged","progress: "+progress);
						seekToPercent = progress*1.0f / seekBar.getMax();
						updateTimeTextView(progress,seekBar.getMax());
					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) 
					{
						videoPlayer.cancelTimer();
					}

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) 
					{
						Log.d("onStopTrackingTouch","seekToPercent: "+seekToPercent);
						videoPlayer.seekToPercent(seekToPercent);
						videoPlayer.startTimer();
					}
        		});
        
        timeTextView = (TextView) findViewById(R.id.timeTextView);
        playButton = (ImageButton) findViewById(R.id.playButton);
        playButton.setOnClickListener(new OnClickListener()
        {
        		@Override
			public void onClick(View v) 
	        	{
	        		onPlayButtonClick();
			}
        });
        
        playButtonLarge = (ImageButton) findViewById(R.id.playButtonLarge);
        playButtonLarge.getDrawable().setAlpha(200);
        playButtonLarge.setOnClickListener(new OnClickListener()
        {
        		@Override
			public void onClick(View v) 
	        	{
        			onPlayButtonClick();
			}
        });
        
        //path = "http://www.androidbook.com/akc/filestorage/android/documentfiles/3389/movie.mp4";
        //path = "http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp";
        //path="http://video19.ifeng.com/video07/2013/08/26/36723-102-055-1208.mp4";
        //path="http://weike.zbedu.net/uploads/media/o2ivPnFYcslItdo.flv";
        //path="http://data.vod.itc.cn/?new=/136/121/lUQsGLAlMbvKE0ZWIEtU1.mp4";
    	
        videoUrl=getIntent().getStringExtra("videoUrl");
        String title=getIntent().getStringExtra("title");
        titleTextView.setText(title);
        
        videoPlayer=new VideoPlayer(surfaceView,this);
        videoPlayer.setVideoUrl(videoUrl);
        videoPlayer.play();
    }

    @Override
   	public void onStart() 
   {
       super.onStart();
       
       ////startTimer();
   }
    
    @Override
	public void onPause() 
    {
        super.onPause();
        
        videoPlayer.pause();
        setPlayButtonPlayingState(false);
    }

    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
        
        videoPlayer.stop();
    }
    
    private void onPlayButtonClick()
    {
    		boolean effectedImmidiately=false;
    		boolean isPlaying=videoPlayer.isPlaying();
		if(isPlaying)
		{
			effectedImmidiately=videoPlayer.pause();
		}
		else
		{
			effectedImmidiately=videoPlayer.play();
			
			if(!effectedImmidiately)
			{
				findViewById(R.id.waitingTextView).setVisibility(View.VISIBLE);
			}
		}
		
		if(effectedImmidiately)
		{
			setPlayButtonPlayingState(!isPlaying);
		}
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) 
    {
    		super.onConfigurationChanged(newConfig);
    	
	    if(newConfig.orientation==ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
	    {
	    		//Toast.makeText(this,"PORTRAIT", Toast.LENGTH_SHORT).show();
	    }
	    else if(newConfig.orientation==ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
	    		|| newConfig.orientation==ActivityInfo.SCREEN_ORIENTATION_USER)
	    {
	    		//Toast.makeText(this,"LANDSCAPE", Toast.LENGTH_SHORT).show();
	    }

	    videoPlayer.updatePlayeViewSize();
    }
    
    private void setPlayButtonPlayingState(boolean isPlayingState)
    {
    		playButton.setSelected(isPlayingState);
    		////middleLayer.setVisibility(isPlayingState?View.GONE:View.VISIBLE);
    }
    
    private void updateTimeTextView(int position,int duration)
    {
    		String positionTimeStr=DateTimeUtil.getTimeString(position);
		String durationTimeStr=DateTimeUtil.getTimeString(duration);
		
		timeTextView.setText(positionTimeStr+" / "+durationTimeStr);
    }
    
    @Override
	public void onVideoPlayerPositionChanged(int position, int duration) 
    {
    		if (duration > 0) 
		{
			if(seekBar.getMax()!=duration)
			{
				seekBar.setMax(duration);
			}
			seekBar.setProgress(position);
			
			updateTimeTextView(position,duration);
		}
	}

	@Override
	public void onVideoPlayerError() 
	{
		findViewById(R.id.waitingTextView).setVisibility(View.GONE);
		CustomDialog.showAlertDialogWithBlock(MediaPlayerActivity.this,"无法播放此视频");
		MediaPlayerActivity.this.onBackPressed();
	}

	@Override
	public void onVideoPlayerBufferingUpdate(int percent) 
	{
		seekBar.setSecondaryProgress(percent*seekBar.getMax()/100);
	}

	@Override
	public void onVideoPlayerPrepared() 
	{
		findViewById(R.id.waitingTextView).setVisibility(View.GONE);
		playButton.setSelected(true);
	}

	@Override
	public void onVideoPlayerCompletion() 
	{
		seekBar.setProgress(0);
		playButton.setSelected(false);
	}

	public void startTimer()
    {
    		mTimerTask = new TimerTask() 
    		{
	    		@Override
	    		public void run() 
	    		{
	    			handler.sendEmptyMessage(0);
	    		}
    		};
    		
    		mTimer=new Timer();
    		mTimer.schedule(mTimerTask, 5000, 5000);
    }
    
    public void cancelTimer()
    {
        if (mTimerTask != null) 
        {  
            mTimerTask.cancel();  
            mTimerTask = null;  
        } 
        
        if (mTimer != null) 
		{  
        		mTimer.cancel();  
        		mTimer = null;  
		}  
    }
}